<template>
	<view class="redEnvelopes" style="background: rgba(244, 239, 230, 1);">
		<view class="" style="background:url(../../static/image/redbackground.png) no-repeat;background-size: 150% 150%;width: 100%;height: 100%;z-index: 999;position: fixed;">
			<view class="title">
				<view class="inline-block left">
					<image src="../../static/image/hongbaoback.png" mode="" @tap="back" style="width: 66upx;height: 66upx;"></image>
				</view>
				<view class="inline-block titleText" :style="i18n.redtitleTextstyle">
					{{i18n.redtitle}}
				</view>
				<view class="redKuang">
					<view class="whiteKuang">
						<text class="text">{{i18n.redquantity}}</text>
						<input type="number" value="" style="width: 75%;text-align:right" @blur="num" placeholder="1-100"
						 placeholder-style="font-size:22upx;font-weight:500" />
						<text>{{i18n.redCompany}}</text>
					</view>
					<view class="" >
						<view class="whiteKuang">
							<text class="text" v-if="type==2" style="width: 400upx;">{{i18n.redAmountEach}}</text>
							<text class="text" v-else  style="width: 400upx;">{{i18n.redAmount}}</text>
							<input type="number" style="text-align:right;" @blur="singleAmount" :placeholder="redAmount"   />
						</view>
					</view>
					<!--可用余额-->
					<view class="AvailableBalance" >
						<text>{{i18n.redBalance}} {{bbalance}} {{symbol}}</text>
					</view>
					<!--选择币种-->
				<view class="" style="position: relative;" @tap="showList">
					<view class="whiteKuang">
						<text class="text"  style="width: 500upx;">{{i18n.redchange}}</text>
						<view class="choice">
							<view class="example-body" >
								<text v-if="symbolList">{{symbol}}</text>	
							</view>
						</view>	
								<image src="../../static/image/hongbaodown.png" mode="" style="width: 21upx;height: 13upx;float: right;"></image>
					</view>
					<!--下拉框-->
					<view class="symolList" v-if="isList" style="position: absolute;top: 80upx;">
						<view class="symbolItem" v-if="symbolList.length >0" @tap="clickItem(item)" v-for="(item,index) in symbolList"
						 :key="index">
							<image v-if="item.assetId==0"  src="../../static/image/icon_detail.png" ></image>
							<image  v-else src="../../static/image/greylogo.png" ></image>
							<text style="margin-top: -10upx;">{{item.assetName}}  ({{item.symbol}})</text>
						</view>
						<view style="text-align: center;" v-else>{{i18n.wzc}}</view>
					</view>
				</view>
					
					<!--选择类型-->
					<view class="SelectType">
						<text>{{i18n.redtype}}</text>
						<view class="packageAll">
							<view class="package" @tap="ordinary(2)">
								<image :src="hongbao ?'../../static/image/hongbaono.png':'../../static/image/hongbaoyes.png'" mode=""></image>
								<div>{{i18n.redNormal}}</div>
							</view>
							<view class="package" @tap="ordinary(1)">
								<image :src="hongbao ?'../../static/image/hongbaoyes.png':'../../static/image/hongbaono.png'" mode=""></image>
								<text>{{i18n.redRadom}}</text>
							</view>
						</view>
					</view>
					<!--备注-->
					<picker v-if="_i18n.locale=='zh_CN'" @change="remarks" :value="index" :range="array" class="remarksstyle">
						<view class="uni-input">{{array[index]}}</view>
						<image src="../../static/image/hongbaodown.png" mode="" style="width: 21upx;height: 13upx;"></image>
					</picker>
					<picker v-else @change="remarks" :value="index" :range="arrayen" class="remarksstyle">
						<view class="uni-input">{{arrayen[index]}}</view>
						<image src="../../static/image/hongbaodown.png" mode="" style="width: 21upx;height: 13upx;"></image>
					</picker>
				</view>
				<!--提交红包-->
				<view class="amountOfMoney" @tap="submit">
					<view class="button">
						<image :src="i18n.redbuttonimg" mode=""></image>
					</view>
				</view>
			</view>
			<password v-if="show" :gasPrice="100" :gasLimit="1000000" @close="close" @callback="callback" :yzpassword="i18n.yzpassword"
			 :btnl="i18n.btn1" :btnr="i18n.btn2" :placeholder="i18n.placeholder" :passprice="i18n.passprice" :pwdtitle="i18n.pwdtitle"
			 :cap="i18n.cap" style="z-index: 4;"></password>
			<image src="../../static/image/hongbaob.png" mode="" class="hongbaob" style="z-index:-1"></image>
			<text class="ps">{{i18n.redps}}</text>
		</view>
	</view>
</template>

<script>
	import account from '../../common/account.js'
	import * as oex from 'oex-web3';
	import payment from '../../common/payment.js'
	import password from '../../components/password/password.vue'
	export default {
		computed: {
			i18n() {
				return this.$t('user')
			}
		},
		components: {

		},

		data() {
			return {
				Envelop: true,
				Envelop2: false,
				//总金额
				// totalAmount: "",
				// //单个金额
				// amount: "",
				numberOfPackets: "",
				tokenlist: ['oex1', 'oex2', 'oex3'],
				index: 0,
				redAmount: "0.00",
				input2: "",
				//红包个数
				hongbaonum: "",
				//红包备注
				// remarkstext: "",
				// 红包发送人账号
				sender: "",
				type: 1,
				symbolList: [], //当前账户所持有的币种列表
				balances: [], //当前账户资产
				assetIdList: "",
				isList: false,
				assetName: "",
				assetId: "",
				decimals: "",
				currentAmount: "",
				symbol: "",
				id: "",
				show: false, //支付密码
				ToaccountName: "",
				hash: "",
				//备注
				array: ['此包只应天上有，人间能得几回收', '问君能有几多愁，恰似一堆红包过期无人收', '纵里寻包千百度，蓦然回首那包却在app里母胎solo', '红包！！！汝来！！！', '发个幸运包，拜了个拜～',
					'此包归我，雨女无瓜', '这个包发的有多大，咱也不知道咱也不敢点', '掐指一算，今日宜收红包忌抠门', '恭喜发财，杠上开花', '发个幸运包，拜了个拜～', '没有什么事是一个红包不能解决的如果不能，再抢一个～',
					'这个包里应该是王炸四个2 …', '我跟你讲，再不点就过期了…', '很想满足不再得瑟发红包，可是臣妾做不到啊...', '此包无银三百两嗯…你要点开康康么？', '不发个红包就闹壳儿疼…', '红包我发了，你随意',
					'每日一醒，包不能停'
				],
				arrayen: ['Alohomora！', 'Bibbidi Bobbidi Boo！', 'XUE HUA PIAO PIAO BEI FENG XIAO XIAO', 'keep calm and OPEN it', 'Life was like a red packet, you never know how much you’re gonna get.',
					'Open it，BITCH！'	],
				index: 0,
				hongbao: true,
				bbalance: "",
				ToaccountName: "redpacketpool",
				allMoney:"",
				// money:''
			}
		},
		onLoad(options) {
			var _this = this
			console.log(_this._i18n.locale)
			uni.getStorage({
				key: 'username',
				success(e) {
					_this.sender = e.data
					_this.getCurrentAccountInfo(); //加载当前账户资产
				}
			})
				if(_this._i18n.locale == 'zh_CN'){
						this.remarkstext = this.array[0]
				}else{
						this.remarkstext = this.arrayen[0]
				}
		

		},
		methods: {
			back() {
				//返回上一页
				this.$CommonJS.navigateBack()
			},
			showList() {
				this.isList = !this.isList;
			},
			clickItem(item) {
				const _this = this
				var symbol = item.symbol
				this.symbol = symbol
				var id = item.assetId
				this.id = id
				var decimals = item.decimals
				this.decimals = decimals
				var balance = item.balance
					//转换数量
				this.bbalance =  balance/Math.pow(10,decimals)
				this.isList = true;
				console.log(_this.isList)
			},
			async getCurrentAccountInfo() {
				//加载当前账户信息
				let _this = this;
				const nodeInfo = uni.getStorageSync('nodeInfo');
				oex.utils.setApp();
				const data = await oex.account.getAccountExByName(_this.sender); //请求参数
				this.$CommonJS.request(nodeInfo, "POST", data).then(res => {
				this.balances = res.data.result.balances;
					if (res.data.result.balances.length > 0) {
						//根据资产id获取资产详情
						_this.getInfoByAssetsID(res.data.result.balances);
					} else {
						_this.symbolList.push(_this._i18n.locale == 'zh_CN' ? '当前账户暂无资产' :
							'There are no assets in the current account')
					}
				}).catch(error => {
					console.log(error)
				})
			},
			getInfoByAssetsID(data) {
				//根据资产id获取资产详情
				if (data.length < 1) {
					uni.hideLoading()
					return;
				}
				const _this = this;
				const nodeInfo = uni.getStorageSync('nodeInfo');
				data.map(item => {
					account.getCoin(nodeInfo, item.assetID).then(result => {
						const asset = {
							assetName: result.data.result.assetName,
							symbol: result.data.result.symbol.toUpperCase(),
							assetId: result.data.result.assetId,
							balance: item.balance,
							decimals: result.data.result.decimals,
						}
						_this.symbolList.push(asset);
						uni.hideLoading()
					})
				})
			},
			//监听单个金额
			singleAmount(e) {
				const _this = this
					_this.totalAmount = e.detail.value
			},

			//实时监听红包个数
			num(e) {
				const _this = this
				_this.hongbaonum=e.detail.value
			},
			//红包类型选择
			ordinary(e) {
				if (e == 1) {
					this.hongbao = !this.hongbao
				} else {
					this.hongbao = !this.hongbao
				}
				this.type = e

			},
			//监听备注
			remarks(e) {
				const _this = this
				this.index = e.target.value
				if(_this._i18n.locale == 'zh_CN'){
						_this.remarkstext = _this.array[e.target.value]
				}else{
						_this.remarkstext = _this.arrayen[e.target.value]
				}
			},
			//提交密码框
			close() {
				//关闭支付框
				this.show = false
			},
			callback(privateKey, gasPrice, gasLimit) {
				const _this = this;
				this.show = false
				this.sender = this.sender.trim();
				var toname = "redpacketpool"
				this.ToaccountName = toname.trim();
				this.id = Number(this.id);
				//支付参数(currentAccountName,toAccountName,assetId,amount,decimals,privateKey,gasPrice,gasLimit)
				payment.payment(_this.sender, _this.ToaccountName, _this.id, _this.allMoney, _this.remarkstext, _this.decimals,
					privateKey, gasPrice, gasLimit, true).then(paymentInfo => {
					_this.hash = paymentInfo
					if (paymentInfo) {
						var url = _this.$API.appServeApi + _this.$API.redgift + '?i18n_language=' + uni.getStorageSync('system_info')
						uni.request({
							url: _this.$API.appServeApi + _this.$API.redgift + '?i18n_language=' + uni.getStorageSync('system_info'),
							method: 'POST',
							header: {
								'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
							},
							data: {
								sender: _this.sender,
								type: String(_this.type),
								number: _this.hongbaonum,
								amount: _this.totalAmount,
								assetid: String(_this.id),
								assetname: _this.symbol,
								remake: _this.remarkstext,
								txhash: _this.hash
							},
							success(res) {
								console.log(res)
								// uni.share({
								//     provider: "weixin",
								//     scene: "WXSceneSession",
								//     type: 0,
								//     href: res.data.data,
								//     title: _this.sender+"红包分享",
								//     summary: _this.remarkstext,
								//     imageUrl: "../../static/image/sharelogo.png",
								//     success: function (res) {
								//         console.log("success:" + JSON.stringify(res));
								//     },
								//     fail: function (err) {
								//         console.log("fail:" + JSON.stringify(err));
								// 								this.$CommonJS.showToast(JSON.stringify(err));
								//     }
								// });
							},
							fail(res) {
								console.log(res)
							}
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			//提交验证
			submit() {
				const _this = this
				//验证id
				if (_this.id.toString()=="") { 
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请选择资产类型' : 'Please select asset type');
					return;
				}
				console.log(_this.totalAmount)
				//验证红包金额
				if (!_this.totalAmount) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入红包金额' : 'Please enter the red envelope amount');
					return;
				}
				//规定红包数量
				if (!_this.hongbaonum) {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入红包数量' : 'Please input the number of red packets');
					return;
				}
					//手气红包
					if(_this.type==1){
						var handred=Number(_this.hongbaonum)
								if(handred<2){
									this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '手气红包数量需大于2个' :
										'The number of lucky red packets should be greater than');
											return;
								}
					}
				var num1 = Number(_this.hongbaonum)
				if (num1 % 1 === 0) {
					if (num1 > 100) {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '一次最多发100个红包' :
							'A maximum of 100 red envelopes can be sent at a time');
						return;
					} else {
						_this.hongbaonum = _this.hongbaonum
				
					}
				} else {
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入正确的红包个数' :
						'Please enter the correct number of red packets');
					return;
				}
				
				//规定红包金额
				var totalAmount=_this.totalAmount
				if(!/^[0-9]*([.][0-9]{1})?$/.test(totalAmount)){
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入一位小数金额' : 'Please enter the amount with one decimal places');
					return;
				}
				//规定红包金额
				var totalAmount=_this.totalAmount
				if(totalAmount/_this.hongbaonum<0.1){
					this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '单个红包金额不得小于0.1' : 'The amount of single red envelope shall not be less than 0.1');
					return;
				}
				
				//普通红包 判断
				if(_this.type==2){
						if (_this.totalAmount > _this.bbalance) {
							this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '输入红包金额已超过资产总额' :
								'The amount of red envelope entered has exceeded the total assets');
								return;
						} else {
								_this.allMoney=Number(_this.totalAmount)*Number(_this.hongbaonum)
								console.log(	_this.allMoney)
						}		
				}else{		
					if (_this.totalAmount > _this.bbalance) {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '输入红包金额已超过资产总额' :
							'The amount of red envelope entered has exceeded the total assets');
							return;
					} else {
								_this.allMoney=Number(_this.totalAmount)
					}	
					
				}
				if (!_this.remarkstext) {
					if(_this._i18n.locale == 'zh_CN'){
										_this.remarkstext = _this.array[0]
					}else{
									_this.remarkstext = _this.arrayen[0]
					}
		
				}
				this.show = true;
			},
		}
	}
</script>

<style lang="stylus">
	@import "../../static/stylus/red_envelopes/red_envelopes.stylus"
	body 
		background #fafafa
</style>
